﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Verifications;

namespace Pixysoft.Framework.Sockets.Core
{
    class ActionHandlerFactory
    {
        private static int default_length_beanid = 3;

        private Dictionary<string, IActionHandler> handlers = new Dictionary<string, IActionHandler>();

        private static volatile ActionHandlerFactory instance;

        private static object syncRoot = new Object();

        public static ActionHandlerFactory Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new ActionHandlerFactory();
                        }
                    }
                }
                return instance;
            }
        }

        public void RegisterHandler(int protocol, int action, IActionHandler command)
        {
            string beanId = "ID"
                    + StringCoder.AddZero(protocol.ToString(), default_length_beanid)
                    + StringCoder.AddZero(action.ToString(), default_length_beanid);

            if (handlers.ContainsKey(beanId))
                throw Exceptions.VerificationFailedException(protocol, action, command);

            handlers.Add(beanId, command);
        }

        public IActionHandler GetHandler(int protocol, int action)
        {
            string beanId = "ID"
                    + StringCoder.AddZero(protocol.ToString(), default_length_beanid)
                    + StringCoder.AddZero(action.ToString(), default_length_beanid);

            if (!handlers.ContainsKey(beanId))
                throw Exceptions.VerificationFailedException(protocol, action);

            return handlers[beanId];
        }

        public void ClearHandlers()
        {
            handlers.Clear();
        }
    }
}
